<template>
  <div class="relative w-full">
    <input
      type="text"
      v-model="searchQuery"
      @input="handleSearch"
      @keyup.enter="handleSubmit"
      placeholder="搜索角色..."
      class="w-full pl-10 pr-4 py-2.5 rounded-xl border border-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all duration-300 bg-gray-800/70 text-white"
    >
    <i class="fa fa-search absolute left-3.5 top-3.5 text-gray-400"></i>
    
    <!-- 搜索建议下拉框 -->
    <div v-if="showSuggestions" class="absolute top-full left-0 right-0 mt-2 glass rounded-xl z-20 max-h-60 overflow-y-auto border border-gray-700 shadow-lg transform transition-all duration-300 opacity-100 scale-100 origin-top">
      <ul class="py-1">
        <li 
          v-for="role in filteredRoles" 
          :key="role.id"
          @click="selectRole(role)"
          class="p-3 hover:bg-gray-800/70 cursor-pointer transition-all duration-300 flex items-center hover:translate-x-1 magic-hover"
        >
          <div v-if="role.avatar" class="w-8 h-8 rounded-full mr-3 overflow-hidden shadow-sm">
            <img :src="role.avatar" :alt="role.name" class="w-full h-full object-cover">
          </div>
          <div v-else class="w-8 h-8 rounded-full mr-3 flex items-center justify-center shadow-sm" :style="{ backgroundColor: generateColorFromText(role.name) }">
            <span :style="{ color: calculateTextColor(role.avatarColor || generateColorFromText(role.name)) }" class="font-medium text-xs">{{ role.name.charAt(0) }}</span>
          </div>
          <div class="flex-1">
            <p class="font-medium text-gray-200">{{ role.name }}</p>
            <p class="text-xs text-gray-500">{{ role.category || role.title || '角色' }}</p>
          </div>
        </li>
      </ul>
      <div v-if="filteredRoles.length === 0" class="p-3 text-gray-400 text-center">
        没有找到相关角色
      </div>
    </div>
    
    <!-- 加载指示器 -->
    <div v-if="isLoading" class="absolute right-3 top-1/2 transform -translate-y-1/2">
      <div class="w-5 h-5 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { searchCharacters } from '../api/roleApi';
import { generateColorFromText, calculateTextColor } from '../utils/index.js';

export default {
  setup(props, { emit }) {
    const searchQuery = ref('');
    const roles = ref([]);
    const filteredRoles = ref([]);
    const showSuggestions = ref(false);
    const searchTimeout = ref(null);
    const isLoading = ref(false);

    // 从API获取角色列表
    const fetchRoles = async () => {
      try {
        // 使用空字符串搜索获取所有角色
        const response = await searchCharacters('');
        if (response && response.code === 200) {
          roles.value = response.data || [];
        }
      } catch (error) {
        console.error('获取角色列表失败:', error);
        // 加载模拟数据
        roles.value = loadMockRoles();
      }
    };

    // 加载模拟角色数据
    const loadMockRoles = () => {
      return [
        {
          id: 1001,
          charId: 1001,
          name: '李白',
          title: '诗仙',
          description: '唐代伟大的浪漫主义诗人，被誉为"诗仙"。李白的诗歌风格豪放飘逸，意境奇妙。',
          avatar: null,
          avatarColor: '#E53935'
        },
        {
          id: 1002,
          charId: 1002,
          name: '爱因斯坦',
          title: '物理学家',
          description: '20世纪最伟大的物理学家之一，相对论的创立者，对现代物理学发展做出了巨大贡献。',
          avatar: null,
          avatarColor: '#1E88E5'
        },
        {
          id: 1003,
          charId: 1003,
          name: '诸葛亮',
          title: '军事家、政治家',
          description: '三国时期蜀汉丞相，杰出的军事家、政治家、文学家、发明家。',
          avatar: null,
          avatarColor: '#43A047'
        },
        {
          id: 1004,
          charId: 1004,
          name: '居里夫人',
          title: '物理学家、化学家',
          description: '首位获得诺贝尔奖的女性，也是唯一一位在两个不同科学领域获得诺贝尔奖的人。',
          avatar: null,
          avatarColor: '#8E24AA'
        },
        {
          id: 1005,
          charId: 1005,
          name: '贝多芬',
          title: '作曲家、钢琴家',
          description: '德国著名作曲家、钢琴家，维也纳古典乐派代表人物之一。',
          avatar: null,
          avatarColor: '#F57C00'
        }
      ];
    };

    // 处理搜索
    const handleSearch = (e) => {
      if (searchTimeout.value) clearTimeout(searchTimeout.value);
      isLoading.value = true;
      searchTimeout.value = setTimeout(async () => {
        try {
          const result = await searchCharacters(searchQuery.value);
          if (result && result.code === 200) {
            filteredRoles.value = result.data || [];
          } else {
            // 如果API调用失败或没有结果，使用本地过滤
            filteredRoles.value = roles.value.filter(role => 
              role.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
              role.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
              role.description.toLowerCase().includes(searchQuery.value.toLowerCase())
            );
          }
          showSuggestions.value = searchQuery.value.trim() !== '' && filteredRoles.value.length > 0;
        } catch (error) {
          console.error('搜索失败:', error);
          // 使用本地过滤作为后备
          filteredRoles.value = roles.value.filter(role => 
            role.name.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
            role.title.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
            role.description.toLowerCase().includes(searchQuery.value.toLowerCase())
          );
          showSuggestions.value = searchQuery.value.trim() !== '' && filteredRoles.value.length > 0;
        } finally {
          isLoading.value = false;
        }
      }, 300);
    };

    // 选择角色
    const selectRole = (role) => {
      // 转换格式以兼容现有逻辑
      const formattedRole = {
        id: role.charId || role.id,
        name: role.name,
        avatar: role.avatarUrl || role.avatar || null,
        avatarColor: role.avatarColor || generateColorFromText(role.name),
        category: role.category,
        title: role.title || '',
        description: role.description || '',
        voiceStyle: role.voiceStyle || 'default'
      };
      emit('roleSelected', formattedRole);
      searchQuery.value = '';
      showSuggestions.value = false;
    };

    // 提交搜索
    const handleSubmit = () => {
      if (filteredRoles.value.length > 0) {
        selectRole(filteredRoles.value[0]);
      }
    };

    // 点击外部关闭下拉框
    const handleClickOutside = (event) => {
      if (!event.target.closest('.relative')) {
        showSuggestions.value = false;
      }
    };

    onMounted(() => {
      fetchRoles();
      document.addEventListener('click', handleClickOutside);
      
      return () => {
        document.removeEventListener('click', handleClickOutside);
      };
    });

    return {
      searchQuery,
      filteredRoles,
      showSuggestions,
      isLoading,
      handleSearch,
      handleSubmit,
      selectRole,
      generateColorFromText
    };
  }
};
</script>

<style scoped>
/* 自定义动画 */
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

.animate-fadeIn {
  animation: fadeIn 0.3s ease-out;
}

/* 魔法效果 */
.magic-hover {
  transition: all 0.3s ease;
}

.magic-hover:hover {
  transform: translateY(-3px);
}

/* 玻璃效果 */
.glass {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: rgba(30, 30, 30, 0.5);
}

::-webkit-scrollbar-thumb {
  background: #6b7280;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #4b5563;
}
</style>
